#!/usr/bin/env bash

# Download an apk from the latest artifact of the production branch
# @param $1 a path to save the apk

set -o pipefail
set -eu

export ASSEMBLE_APK_JOB_NAME="assemble_apk"
export PRODUCTION_BRANCH="master" # assume master is a production build

CIRCLECI_API_URL="https://circleci.com/api/v1.1/project/github/$PROJECT_SLUG"

latest_build_num() {
  curl "${CIRCLECI_API_URL}?filter=completed" | \
      ruby -rjson -e 'puts JSON.parse(STDIN.read).find { |j| j["branch"] == ENV.fetch("PRODUCTION_BRANCH") && j["build_parameters"]["CIRCLE_JOB"] == ENV.fetch("ASSEMBLE_APK_JOB_NAME") }["build_num"]'
}

artifacts() {
  local -r build_num="$1"
  curl "${CIRCLECI_API_URL}/${build_num}/artifacts"
}

grep_apk_url() {
    cat - | ruby -rjson -e 'puts JSON.parse(STDIN.read).map { |j| j["url"] }.join("\n")' | grep "apk" | head -1 # find first
}

download_latest_apk() {
  local -r save_to="$1"
  local apk_url=$(artifacts $(latest_build_num) | grep_apk_url)

  curl -o "${save_to}" "${apk_url}"
}

download_latest_apk "$1"
